/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/*
 * XlsLoaderClient.java
 *
 * Created on 30/11/2010, 06:26:45 PM
 */

package client;

import bo.*;
import java.awt.Desktop;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Vector;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JFileChooser;
import javax.swing.JOptionPane;

/**
 *
 * @author PC PERU
 */
public class XlsLoaderClient extends javax.swing.JFrame {

    /** Creates new form XlsLoaderClient */
    public XlsLoaderClient() {
        super("Moodle");
        initComponents();

    }
    String archivo="";
    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jbAceptar = new javax.swing.JButton();
        jbCancelar = new javax.swing.JButton();
        jbAbrir = new javax.swing.JButton();
        jtxtArchivo = new javax.swing.JTextField();
        jLabel1 = new javax.swing.JLabel();
        jbVer = new javax.swing.JButton();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);

        jbAceptar.setText("Aceptar");
        jbAceptar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jbAceptarActionPerformed(evt);
            }
        });

        jbCancelar.setText("Cancelar");
        jbCancelar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jbCancelarActionPerformed(evt);
            }
        });

        jbAbrir.setText("Abrir...");
        jbAbrir.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jbAbrirActionPerformed(evt);
            }
        });

        jtxtArchivo.setText("C:\\");

            jLabel1.setIcon(new javax.swing.ImageIcon("C:\\Users\\Mendoza\\Documents\\bd2\\XlsToDatabase\\src\\resource\\moodle.JPG")); // NOI18N

            jbVer.setText("Ver Archivo");
            jbVer.addActionListener(new java.awt.event.ActionListener() {
                public void actionPerformed(java.awt.event.ActionEvent evt) {
                    jbVerActionPerformed(evt);
                }
            });

            javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
            getContentPane().setLayout(layout);
            layout.setHorizontalGroup(
                layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                .addGroup(layout.createSequentialGroup()
                    .addContainerGap()
                    .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                        .addComponent(jLabel1)
                        .addComponent(jtxtArchivo, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, 588, Short.MAX_VALUE)
                        .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                            .addGap(50, 50, 50)
                            .addComponent(jbVer, javax.swing.GroupLayout.PREFERRED_SIZE, 102, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 127, Short.MAX_VALUE)
                            .addComponent(jbAceptar, javax.swing.GroupLayout.PREFERRED_SIZE, 97, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addGap(116, 116, 116)
                            .addComponent(jbCancelar, javax.swing.GroupLayout.PREFERRED_SIZE, 96, javax.swing.GroupLayout.PREFERRED_SIZE)))
                    .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                    .addComponent(jbAbrir)
                    .addContainerGap())
            );
            layout.setVerticalGroup(
                layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                    .addComponent(jLabel1, javax.swing.GroupLayout.PREFERRED_SIZE, 64, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addGap(24, 24, 24)
                    .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                        .addComponent(jtxtArchivo, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addComponent(jbAbrir))
                    .addGap(48, 48, 48)
                    .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                        .addComponent(jbCancelar, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                        .addComponent(jbAceptar)
                        .addComponent(jbVer, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
                    .addGap(36, 36, 36))
            );

            pack();
        }// </editor-fold>//GEN-END:initComponents

    private void jbAbrirActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jbAbrirActionPerformed
        // TODO add your handling code here:
        JFileChooser fileChooser = new JFileChooser();
        int res = fileChooser.showOpenDialog(null);
        if(res == JFileChooser.APPROVE_OPTION){
            File file = fileChooser.getSelectedFile();
            archivo=String.valueOf(file);
            jtxtArchivo.setText(String.valueOf(file));
        }
    }//GEN-LAST:event_jbAbrirActionPerformed

    private void jbCancelarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jbCancelarActionPerformed
        // TODO add your handling code here:
        int confirmed=JOptionPane.showConfirmDialog(this, "Esta seguro que desea cancelar la operación?", "Confirmacion",JOptionPane.YES_NO_OPTION,JOptionPane.QUESTION_MESSAGE);
        if(confirmed==JOptionPane.NO_OPTION)  return;
        System.exit(0);
        //setVisible(false);
        //System.exit(0);
        //EXIT_ON_CLOSE;//EXIT_ON_CLOSE();
    }//GEN-LAST:event_jbCancelarActionPerformed

    private void jbVerActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jbVerActionPerformed
        // TODO add your handling code here:
       
        if(archivo.length()==0){
            JOptionPane.showMessageDialog(null, "Seleccione un archivo para poder verlo.", "Error", JOptionPane.ERROR_MESSAGE);
            return;
        }
        try {
             File path = new File (archivo);
             Desktop.getDesktop().open(path);
        }catch (IOException ex) {
             ex.printStackTrace();
        }
    }//GEN-LAST:event_jbVerActionPerformed

    ///COPIO ARCHIVO SELECCIONADO AL PROYECTO PARA PODER EJECUTARLO DE MANERA CORRECTA
    public static void copyfile(String srFile, String dtFile){
    try{
      File f1 = new File(srFile);
      File f2 = new File(dtFile);
      InputStream in = new FileInputStream(f1);

      OutputStream out = new FileOutputStream(f2);

      byte[] buf = new byte[1024];
      int len;
      while ((len = in.read(buf)) > 0){
        out.write(buf, 0, len);
      }
      in.close();
      out.close();
    }
    catch(FileNotFoundException ex){
      System.out.println(ex.getMessage() + " in the specified directory.");
      System.exit(0);
    }
    catch(IOException e){
      System.out.println(e.getMessage());
    }
  }

    private void jbAceptarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jbAceptarActionPerformed
        // TODO add your handling code here:
        /*if(!archivo.endsWith(".txt")){
            JOptionPane.showMessageDialog(null, "Seleccione un archivo con formato .txt Unicode.", "Error", JOptionPane.ERROR_MESSAGE);
            return;
        }*/
        if(archivo.length()==0){
            JOptionPane.showMessageDialog(null, "Seleccione un archivo.", "Error", JOptionPane.ERROR_MESSAGE);
            return;
        }
        String nombre="";
        for(int i=archivo.length()-1;i>=0;i--){

            if(archivo.charAt(i)=='\\'){
                break;
            }
            nombre=archivo.charAt(i)+nombre;
        }
        String origen="C:\\Users\\Mendoza\\Documents\\bd2\\XlsToDatabase\\"+nombre;
        copyfile(archivo,origen);
        try {
            new XlsLoader(archivo).load();
            /*
            Vector<Vector<String> >vs= new Vector<Vector<String> >();
            try {
            vs = xls.getData();
            } catch (Exception ex) {
            Logger.getLogger(XlsLoaderClient.class.getName()).log(Level.SEVERE, null, ex);
            }
            for(int i=0; i<vs.size(); i++){
            for(int j=0; j<vs.get(i).size(); j++){
            System.out.print(vs.get(i).get(j)+" ");
            }
            System.out.print("\n");
            }
             *
             */
        } catch (Exception ex) {
            Logger.getLogger(XlsLoaderClient.class.getName()).log(Level.SEVERE, null, ex);
        }


    }//GEN-LAST:event_jbAceptarActionPerformed

    /**
    * @param args the command line arguments
    */
    public static void main(String args[]) {
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                new XlsLoaderClient().setVisible(true);
            }
        });
    }

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JLabel jLabel1;
    private javax.swing.JButton jbAbrir;
    private javax.swing.JButton jbAceptar;
    private javax.swing.JButton jbCancelar;
    private javax.swing.JButton jbVer;
    private javax.swing.JTextField jtxtArchivo;
    // End of variables declaration//GEN-END:variables

}
